using System.Collections.Generic;
using Ardal.MSBuildShellExtension.DomainModel.API;
using Microsoft.Win32;
using System.Text;
using System.Reflection;

/*
 * Copyright (c) 2007-2008, Thomas Ardal (thomasardalatgmail.com)
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
 *
 * * Neither the name of Thomas Ardal nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
namespace Ardal.MSBuildShellExtension.DomainModel.Impl
{
    internal class ConfigRegistryProvider : IConfigRegistryProvider
    {
        #region IConfigProvider Members

        public IList<IEditor> GetEditors()
        {
            IList<IEditor> editors = new List<IEditor>();
            RegistryKey editorsKey = Registry.CurrentUser.OpenSubKey("Software\\Ardal\\MSBuildShellExtension\\Editors");
            foreach (string regEditor in editorsKey.GetSubKeyNames())
            {
                string fullKey = editorsKey + "\\" + regEditor;
                bool defaultEditor = bool.Parse((string)Registry.GetValue(fullKey, "DefaultEditor", null));
                string filename = (string)Registry.GetValue(fullKey, "Filename", null);
                string arguments = (string)Registry.GetValue(fullKey, "Arguments", null);
                IEditor editor = new Editor(regEditor, filename, arguments, defaultEditor);
                editors.Add(editor);
            }

            return editors;
        }

        public void SaveEditor(IEditor editor)
        {
            if (editor.Modified)
            {
                RegistryKey targetKey = Registry.CurrentUser.OpenSubKey("Software\\Ardal\\MSBuildShellExtension\\Editors", true);
                DeleteSubKeyIfExists(targetKey, editor.Title);
                if (!editor.Deleted)
                {
                    RegistryKey newEditorKey = targetKey.CreateSubKey(editor.Title);
                    Registry.SetValue(newEditorKey.ToString(), "DefaultEditor", editor.DefaultEditor);
                    Registry.SetValue(newEditorKey.ToString(), "Filename", editor.Filename);
                    Registry.SetValue(newEditorKey.ToString(), "Arguments", editor.Arguments);
                }
            }
        }

        public void SaveTarget(ITarget target)
        {
            if (target.Modified)
            {
                RegistryKey targetKey = Registry.CurrentUser.OpenSubKey("Software\\Ardal\\MSBuildShellExtension\\Targets", true);
                DeleteSubKeyIfExists(targetKey, target.Title);
                if (!target.Deleted)
                {
                    RegistryKey newTargetKey = targetKey.CreateSubKey(target.Title);
                    Registry.SetValue(newTargetKey.ToString(), "MSBuildTarget", target.MSBuildTarget);
                    Registry.SetValue(newTargetKey.ToString(), "Verbosity", MSBuildConvertions.VerbosityEnumToString(target.Verbosity));
                    Registry.SetValue(newTargetKey.ToString(), "Configuration", MSBuildConvertions.ConfigurationEnumToString(target.Configuration));
                    Registry.SetValue(newTargetKey.ToString(), "ShowLogger", target.ShowErrorList);
                }
            }
        }

        public void SaveExtension(IExtension extension)
        {
            if (extension.Modified)
            {
                RegistryKey extensionsKey = Registry.CurrentUser.OpenSubKey("Software\\Ardal\\MSBuildShellExtension\\Extensions", true);
                DeleteSubKeyIfExists(extensionsKey, extension.FileExtension);
                if (!extension.Deleted)
                {
                    RegistryKey newExtensionKey = extensionsKey.CreateSubKey(extension.FileExtension);
                    StringBuilder targetsBuilder = new StringBuilder();
                    foreach (ITarget target in extension.Targets)
                    {
                        targetsBuilder.Append(target.Title + ";");
                    }
                    Registry.SetValue(newExtensionKey.ToString(), "Targets", targetsBuilder.ToString().TrimEnd(new char[] { ';' }));
                    if (string.IsNullOrEmpty(extension.DotNetVersion))
                    {
                        extension.DotNetVersion = "v2.0.50727";
                    }
                    Registry.SetValue(newExtensionKey.ToString(), "DotNetVersion", extension.DotNetVersion);

                    RegistryKey targetKey = Registry.ClassesRoot.OpenSubKey("SystemFileAssociations\\." + extension.FileExtension + "\\shell", true);
                    if (targetKey == null)
                    {
                        targetKey = Registry.ClassesRoot.CreateSubKey("SystemFileAssociations\\." + extension.FileExtension + "\\shell");
                    }
                    foreach (ITarget target in extension.Targets)
                    {
                        DeleteSubKeyIfExists(targetKey, target.Title);
                        if (!target.Deleted && !extension.ToDeleteTargets.Contains(target))
                        {
                            RegistryKey newTargetKey = targetKey.CreateSubKey(target.Title + "\\command");
                            StringBuilder targetBuilder = new StringBuilder();
                            targetBuilder.Append("cmd.exe /k \"\"%%windir%%\\Microsoft.NET\\Framework\\" + extension.DotNetVersion + "\\MSBuild.exe\" \"%1\" ");
                            targetBuilder.Append("/t:" + target.MSBuildTarget + " ");
                            targetBuilder.Append("/v:" + MSBuildConvertions.VerbosityEnumToString(target.Verbosity) + " ");
                            targetBuilder.Append("/p:Configuration=" + MSBuildConvertions.ConfigurationEnumToString(target.Configuration));
                            if (target.ShowErrorList)
                            {
                                string filename = Assembly.GetExecutingAssembly().Location;
                                string location = filename.Substring(0, filename.LastIndexOf("\\"));
                                targetBuilder.Append(" /l:MSBuildErrorListLogger,\"" + location + "\\MSBuildShellExtension.dll\"");
                            }
                            targetBuilder.Append("\" & exit");
                            Registry.SetValue(newTargetKey.ToString(), "", targetBuilder.ToString());
                        }
                    }
                    foreach (ITarget deleteTarget in extension.ToDeleteTargets)
                    {
                        DeleteSubKeyIfExists(targetKey, deleteTarget.Title);
                    }
                    extension.ToDeleteTargets.Clear();
                }
            }
        }

        private static void DeleteSubKeyIfExists(RegistryKey filetypeKey, string p)
        {
            foreach (string subKey in filetypeKey.GetSubKeyNames())
            {
                if (subKey.Equals(p))
                {
                    filetypeKey.DeleteSubKeyTree(p);
                }
            }
        }

        public IList<ITarget> GetTargets()
        {
            IList<ITarget> targets = new List<ITarget>();
            RegistryKey targetsKey = Registry.CurrentUser.OpenSubKey("Software\\Ardal\\MSBuildShellExtension\\Targets");
            foreach (string regTarget in targetsKey.GetSubKeyNames())
            {
                string fullKey = targetsKey + "\\" + regTarget;
                string msbuildTarget = (string)Registry.GetValue(fullKey, "MSBuildTarget", null);
                Verbosity verbosity = MSBuildConvertions.VerbosityStringToEnum((string)Registry.GetValue(fullKey, "Verbosity", null));
                Configuration configuration = MSBuildConvertions.ConfigurationStringToEnum((string)Registry.GetValue(fullKey, "Configuration", null));
                bool showLogger = bool.Parse((string)Registry.GetValue(fullKey, "ShowLogger", null));
                ITarget target = new Target(regTarget, msbuildTarget, verbosity, configuration, showLogger);
                targets.Add(target);
            }
            return targets;
        }

        public IList<IExtension> GetExtensions(IList<ITarget> targets)
        {
            IDictionary<string, ITarget> targetDic = new Dictionary<string, ITarget>();
            foreach (ITarget target in targets)
            {
                targetDic.Add(target.Title, target);
            }

            IList<IExtension> extensions = new List<IExtension>();
            RegistryKey extensionsKey = Registry.CurrentUser.OpenSubKey("Software\\Ardal\\MSBuildShellExtension\\Extensions");
            foreach (string regExtension in extensionsKey.GetSubKeyNames())
            {
                string fullKey = extensionsKey + "\\" + regExtension;
                string targetString = (string)Registry.GetValue(fullKey, "Targets", null);
                IList<ITarget> extensionTargets = new List<ITarget>();
                string[] targetsToAdd = targetString.Split(new char[] { ';' });
                //Do not add targets, if not targets are defined
                if (!(targetsToAdd.Length == 1 && targetsToAdd[0].Equals("")))
                {
                    foreach (string s in targetsToAdd)
                    {
                        if (targetDic.ContainsKey(s))
                        {
                            extensionTargets.Add(targetDic[s]);
                        }
                    }
                }
                string dotNetVersionString = (string) Registry.GetValue(fullKey, "DotNetVersion", null);
                IExtension extension = new Extension(regExtension, dotNetVersionString, extensionTargets);
                extensions.Add(extension);
            }
            return extensions;
        }

        #endregion
    }
}
